<template>
  <div class="data-dashboard">
    <!-- 返回按钮 -->
    <div class="back-button" @click="goBack">返回</div>

    <!-- 图表布局 -->
    <div class="dashboard-grid">
      <!-- 上部分图表 -->
      <div class="chart-row">
        <div class="chart-container" id="participation-chart"></div>
        <div class="chart-container" id="boxplot-chart"></div>
        <div class="chart-container" id="pie-chart"></div>
      </div>

      <!-- 下部分图表 -->
      <div class="chart-row">
        <div class="chart-container" id="trend-chart"></div>
        <div class="chart-container" id="liquid-chart"></div>
        <div class="chart-container" id="wordcloud-chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import * as echarts from 'echarts'
import 'echarts-liquidfill'
import 'echarts-wordcloud'

const router = useRouter()

// 图表实例
const charts = ref({
  participationChart: null,
  boxplotChart: null,
  pieChart: null,
  trendChart: null,
  liquidChart: null,
  wordcloudChart: null
})

// 返回上一页
const goBack = () => {
  router.push('athlete-analysis')
}

// 初始化参赛人员变化分析图
const initParticipationChart = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/olympic_people', {
      params: { country: '不选择' }
    })

    if (response.data.success) {
      const data = response.data.data
      const years = data.map(item => item.Year)
      const summerData = data.map(item => item.summer)
      const winterData = data.map(item => item.winter)

      const option = {
        title: { text: '参赛人员变化分析', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { data: ['夏季', '冬季'], top: 30 },
        xAxis: { type: 'category', data: years },
        yAxis: { type: 'value' },
        series: [
          {
            name: '夏季',
            type: 'line',
            data: summerData,
            smooth: true
          },
          {
            name: '冬季',
            type: 'line',
            data: winterData,
            smooth: true
          }
        ]
      }
      charts.value.participationChart.setOption(option)
    }
  } catch (error) {
    console.error('初始化参赛人员变化分析图失败：', error)
  }
}

// 初始化年龄分布图表
const initAgeDistributionCharts = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/olympic_gender', {
      params: {
        country: '不选择',
        sport: '不选择'
      }
    })

    if (response.data.success) {
      // 箱型图配置
      const boxplotOption = {
        title: { text: '运动员年龄分布箱型图', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { data: ['男性', '女性'], top: 30 },
        xAxis: { type: 'category', data: [...new Set(response.data.data.map(item => item.Year))] },
        yAxis: { type: 'value', name: '年龄' },
        series: [
          {
            name: '男性',
            type: 'boxplot',
            data: response.data.data.filter(item => item.Sex === 'M').map(item => [
              item.min, item['25%'], item['50%'], item['75%'], item.max
            ])
          },
          {
            name: '女性',
            type: 'boxplot',
            data: response.data.data.filter(item => item.Sex === 'F').map(item => [
              item.min, item['25%'], item['50%'], item['75%'], item.max
            ])
          }
        ]
      }
      charts.value.boxplotChart.setOption(boxplotOption)

      // 饼图配置
      const pieOption = {
        title: { text: '运动员性别比例', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { orient: 'horizontal', top: 30 },
        series: [{
          type: 'pie',
          radius: '50%',
          data: response.data.proportion.map(([gender, value]) => ({
            name: gender === 'M' ? '男性' : '女性',
            value: value
          }))
        }]
      }
      charts.value.pieChart.setOption(pieOption)
    }
  } catch (error) {
    console.error('初始化年龄分布图表失败：', error)
  }
}

// 初始化身高体重趋势图
const initHeightWeightTrend = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/height_weight_correlation', {
      params: {
        country: '不选择',
        sport: '不选择'
      }
    })

    if (response.data.success) {
      const { grouped_data } = response.data.data
      const maleData = grouped_data.filter(item => item.Sex === 'M')
      const femaleData = grouped_data.filter(item => item.Sex === 'F')

      const option = {
        title: { text: '男女运动员身高体重变化趋势', left: 'center' },
        tooltip: { trigger: 'axis' },
        legend: { data: ['男性身高', '男性体重', '女性身高', '女性体重'], top: 30 },
        xAxis: { type: 'category', data: [...new Set(grouped_data.map(item => item.Year))].sort() },
        yAxis: [
          { name: '身高 (cm)', type: 'value', min: 150, max: 200 },
          { name: '体重 (kg)', type: 'value', min: 50, max: 120 }
        ],
        series: [
          { name: '男性身高', type: 'line', data: maleData.map(item => item.Height) },
          { name: '男性体重', type: 'line', yAxisIndex: 1, data: maleData.map(item => item.Weight) },
          { name: '女性身高', type: 'line', data: femaleData.map(item => item.Height) },
          { name: '女性体重', type: 'line', yAxisIndex: 1, data: femaleData.map(item => item.Weight) }
        ]
      }
      charts.value.trendChart.setOption(option)
    }
  } catch (error) {
    console.error('初始化身高体重趋势图失败：', error)
  }
}

// 初始化奖牌分析图
const initMedalAnalysis = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/medal_analysis', {
      params: {
        year: '不选择',
        country: '不选择'
      }
    })

    if (response.data.success) {
      const option = {
        title: { text: '奖牌获得情况', left: 'center' },
        series: [{
          type: 'liquidFill',
          data: [response.data.data.count_data.total_medal_proportion / 100],
          radius: '80%',
          label: {
            formatter: `${response.data.data.count_data.total_medal_proportion.toFixed(2)}%`
          }
        }]
      }
      charts.value.liquidChart.setOption(option)
    }
  } catch (error) {
    console.error('初始化奖牌分析图失败：', error)
  }
}

// 初始化项目分析词云图
const initSportsAnalysis = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/get_top_sports', {
      params: {
        country: '不选择',
        year: '不选择'
      }
    })

    if (response.data.success) {
      const option = {
        title: { text: '国家强势项目词云图', left: 'center' },
        series: [{
          type: 'wordCloud',
          shape: 'circle',
          left: 'center',
          top: 'center',
          width: '70%',
          height: '80%',
          right: null,
          bottom: null,
          sizeRange: [12, 60],
          rotationRange: [-90, 90],
          rotationStep: 45,
          gridSize: 8,
          drawOutOfBound: false,
          textStyle: {
            fontFamily: 'sans-serif',
            fontWeight: 'bold',
            color: () => 'rgb(' + [Math.round(Math.random() * 160), Math.round(Math.random() * 160), Math.round(Math.random() * 160)].join(',') + ')'
          },
          data: response.data.data.world_data.map(item => ({
            name: item,
            value: Math.round(Math.random() * 100 + 100)
          }))
        }]
      }
      charts.value.wordcloudChart.setOption(option)
    }
  } catch (error) {
    console.error('初始化项目分析词云图失败：', error)
  }
}

// 初始化所有图表
const initAllCharts = () => {
  charts.value.participationChart = echarts.init(document.getElementById('participation-chart'))
  charts.value.boxplotChart = echarts.init(document.getElementById('boxplot-chart'))
  charts.value.pieChart = echarts.init(document.getElementById('pie-chart'))
  charts.value.trendChart = echarts.init(document.getElementById('trend-chart'))
  charts.value.liquidChart = echarts.init(document.getElementById('liquid-chart'))
  charts.value.wordcloudChart = echarts.init(document.getElementById('wordcloud-chart'))

  initParticipationChart()
  initAgeDistributionCharts()
  initHeightWeightTrend()
  initMedalAnalysis()
  initSportsAnalysis()
}

// 处理窗口大小变化
const handleResize = () => {
  Object.values(charts.value).forEach(chart => chart?.resize())
}

onMounted(() => {
  initAllCharts()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  Object.values(charts.value).forEach(chart => chart?.dispose())
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.data-dashboard {
  width: 100vw;
  height: 100vh;
  background-color: #f0f2f5;
  padding: 20px;
  position: relative;
  box-sizing: border-box;
}

.back-button {
  position: fixed;
  top: 20px;
  left: 20px;
  padding: 10px 20px;
  background-color: #1e90ff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.back-button:hover {
  background-color: #40a9ff;
}

.arrow {
  margin-right: 8px;
  font-size: 18px;
}

.dashboard-grid {
  height: calc(100% - 60px);
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 40px;

}

.chart-row {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.chart-container {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  height: 100%;
  min-height: 300px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
